package com.wxyzz.canteenadmin.sys.controller;

import com.wf.captcha.utils.CaptchaUtil;
import com.wxyzz.canteenadmin.sys.param.LoginParam;
import com.wxyzz.canteenadmin.sys.service.SysUserService;
import com.wxyzz.canteencommon.common.R;
import com.wxyzz.canteencommon.entity.sys.SysUser;
import com.wxyzz.canteencommon.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/10/6
 * @Solgne 从想做到能做
 * @Desc
 */
@RestController
@RequestMapping("/sys/user")
@CrossOrigin
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    //@MyLog("登录")
    @PostMapping("/login")
    public R login (@RequestBody LoginParam loginParam, HttpSession session,HttpServletRequest request) {
        if (!CaptchaUtil.ver(loginParam.getVerCode(), request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return R.fail("验证码不正确");
        }
        SysUser sysUser = sysUserService.login(loginParam);
        if (sysUser!=null){
            session.setAttribute("userInfo",sysUser);
            String token = UUID.randomUUID().toString().replace("-", "");
            RedisUtils.setValueTimeout(token, sysUser,3600);
            HashMap<String, String> map = new HashMap<>();
            map.put("token", token);
            return R.ok(map);
        }
        return R.fail();
    }

    @GetMapping("/info")
    public R getUserInfo(HttpSession session){
        SysUser info = (SysUser) session.getAttribute("userInfo");
        return R.ok(info);
    }


    @PostMapping("/logout")
    public R logout(HttpSession session, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        session.invalidate();
        RedisUtils.delKey(token);
        return R.ok();
    }
}
